<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>测试</title>
<style type="text/css">
#code{
	width:500px;
	height:200px;
}
#hint{
	padding:8px;
	border-left:2px solid #ccc;
	background-color:#eee;
	word-wrap:break-word;
	font-size:14px;
	color:#4d4d4d;
	line-height:1.5;
	font-family:consolas;
}
.xml-comment{color:#999;}
.xml-string{color:#00f;}
.xml-tag{color:#009;}
.xml-link{color:#060;}
.xml-img{color:#909;}
.xml-form{color:#f90;}
.xml-table{color:#099;}
</style>
</head>

<body>
<textarea id="code">
<span>&nbsp;</span>

</textarea>
<button id="btn">format</button>
<div id="hint" ></div>

<script type="text/javascript">
(function(){
	var reg, i,
		tableList="table|thead|tbody|tfoot|td|th|tr",
		formList="form|input|select|option|textarea",
		elCode = document.getElementById('code'),
		elShow = document.getElementById('hint');
	
	document.getElementById('btn').onclick = function(){
		var value = elCode.value;
		var objBuff = [];
		var scriptList = [];
		var j = 0;
		i = 0;
		value = value.replace(/&(\S+?;)/g, '&amp;$1').replace(/</g, '&lt;').replace(/>/g, '&gt;');
		
		//注释
		value = value.replace(/&lt;!--(?:.|\n)+?--&gt;/g, function(val){
			objBuff.push({
				cls: 'xml-comment',
				value: val
			});
			return '__tmpBuff' + i++ + '__';
		});
		
		//字符串
		value = value.replace(/([^\\])?((\"|\').*?([^\\])\3)/g, function(val){
			return '<span class="xml-string">' + val + '</span>';
		});
		
		//html元素
		value = value.replace(/&lt;\/?([a-z]+)(?:.|\n)*?&gt;/g, function(m, n){
			
			reg = new RegExp('^' + tableList + '$', 'gi');
			if(reg.test(n)){
				return '<span class="xml-table">' + m + '</span>';
			}
			reg = new RegExp('^' + formList + '$', 'gi');
			if(reg.test(n)){
				return '<span class="xml-form">' + m + '</span>';
			}
			switch(n){
				case 'img':
					return '<span class="xml-img">' + m + '</span>';
				case 'a':
					return '<span class="xml-link">' + m + '</span>';
				default:
					return '<span class="xml-tag">' + m + '</span>';
			}
		});
		
		value = value.replace(/__tmpBuff(\d+)__/g, function(val, index){
			return '<span class="' + objBuff[index].cls + '">' + objBuff[index].value + '</span>';
		});
		
		value = value.replace(/^\t+/gm, function(val){
			return (new Array(val.length + 1)).join('&nbsp;&nbsp;&nbsp;&nbsp;');
		});
		value = value.replace(/^ +/gm, function(val){
			return (new Array(val.length + 1)).join('&nbsp;');
		});
		
		value = value.replace(/\r?\n/g, function(val){
			return '<br />';
		});
		
		elShow.innerHTML = value;
	};
})();
</script>
</body>
</html>